﻿using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace UDITest
{
    internal class CameraTool
    {
        VideoCaptureDevice _camera;
        Action<Bitmap> _videoAction;

        public void Conn(string cameraName, Action<Bitmap> videoAction)
        {
            var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            foreach (FilterInfo device in videoDevices)
            {
                if (device.Name.Equals(cameraName, StringComparison.OrdinalIgnoreCase))
                {
                    _camera = new VideoCaptureDevice(device.MonikerString);

                    _camera.NewFrame += _camera_NewFrame;

                    _videoAction = videoAction;

                    _camera.Start();
                    return;
                }
            }

            throw new Exception("无法连接摄像头");
        }

        private void _camera_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            _videoAction?.Invoke(eventArgs.Frame.Clone() as Bitmap);
            eventArgs.Frame.Dispose();
            GC.Collect();
        }

        // 关闭并释放摄像头
        public void ShutCamera()
        {
            if (_camera != null)
            {
                Task.Run(() =>
                {
                    _camera.NewFrame -= _camera_NewFrame;
                    _camera.SignalToStop();
                    _camera.WaitForStop();
                });

            }
        }

    }
}
